package com.businesswebsite.businesswebsite.FormalWebExplot.Controller;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.businesswebsite.businesswebsite.FormalWebExplot.DTO.UserHolder;
import com.businesswebsite.businesswebsite.FormalWebExplot.Entity.CompanyUser;
import com.businesswebsite.businesswebsite.FormalWebExplot.Service.User.CompanyUserService;
import com.businesswebsite.businesswebsite.FormalWebExplot.Service.impl.User.CompanyUserImpl;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.Renum;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.Result;
import com.businesswebsite.businesswebsite.FormalWebExplot.Utils.ResultUtil;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

import static org.springframework.util.ObjectUtils.isEmpty;

@CrossOrigin(origins = "http://47.108.80.35:8080" , allowCredentials = "true")
//@CrossOrigin(origins = "http://localhost:8080" , allowCredentials = "true")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private CompanyUserService companyUserService;
//  用户登陆
    @PostMapping("/login")
//    @RequestParam("user_account")String user_account, @RequestParam("password") String password
    public Result Login(@RequestBody CompanyUser companyUser) {
        try{
            String  md5Password = DigestUtils.md5DigestAsHex(companyUser.getPassword().getBytes(StandardCharsets.UTF_8));
            companyUser.setPassword(md5Password);
            UsernamePasswordToken token = new UsernamePasswordToken(companyUser.getUser_account(), companyUser.getPassword());

            Subject user = SecurityUtils.getSubject();
            user.login(token);
            CompanyUser loginUser = (CompanyUser) user.getPrincipal();
            UserHolder userHolder = new UserHolder();
            BeanUtil.copyProperties(loginUser,userHolder);
            // 把loginUser转化成Json格式
            JSONObject json = (JSONObject) JSONObject.toJSON(userHolder);
            if( !isEmpty(loginUser) ){
                return ResultUtil.success(json);
            }
            return ResultUtil.error(Renum.USER_PASSWORD_ERROR.getCode(), Renum.USER_PASSWORD_ERROR.getMsg());
        }catch (Exception e){
            return ResultUtil.error(Renum.UNKNOWN_ERROR.getCode(),e.getMessage());
        }
    }
//  登陆根据账号查询id然后修改密码
    @PutMapping("/update")
    public Result update(@RequestBody CompanyUser companyUser){
        try{
            CompanyUser companyUser1 = companyUserService.SelectByAccount(companyUser.getUser_account());
            if (companyUser1 == null){
                return ResultUtil.error(Renum.USER_NOT_EXIST.getCode(), Renum.USER_NOT_EXIST.getMsg());
            }else {
                companyUser.setUser_id(companyUser1.getUser_id());
                Integer update = companyUserService.Update(companyUser);
                if (update != null){
                    return ResultUtil.success(update+"用户密码修改成功");
                }else{
                    return ResultUtil.error(Renum.ERROR.getCode(), Renum.ERROR.getMsg());
                }
            }
        }catch (Exception e){
            return ResultUtil.error(Renum.UNKNOWN_ERROR.getCode(),e.getMessage());
        }
    }

//    注册
    @PostMapping("/register")
    public Result register(@RequestBody CompanyUser companyUser){
        try{
            String user_id = UUID.randomUUID().toString().replace("-","");
            companyUser.setUser_id(user_id);
            Integer register = companyUserService.Register(companyUser);
            return ResultUtil.success(register+"用户注册成功");
        }catch (Exception e){
            return ResultUtil.error(Renum.UNKNOWN_ERROR.getCode(),e.getMessage());
        }
    }
//    注销用户
    @DeleteMapping("/delete")
    public Result delete(@RequestParam("user_account")String user_account){
        try{
            if(user_account !=null) {
                Integer delete = companyUserService.Delete(user_account);
                return ResultUtil.success(delete);
            }else{
                throw new RuntimeException(Renum.ERROR.getCode()+":"+Renum.ERROR.getMsg());
            }
        }catch (Exception e){
            return ResultUtil.error(Renum.UNKNOWN_ERROR.getCode(),e.getMessage());
        }
    }

    // 登录检测
    @GetMapping("/info")
    public Result info(){
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()){
            CompanyUser user = (CompanyUser)currentUser.getPrincipal();
            return ResultUtil.success(user);
        }else{
            return ResultUtil.error(Renum.UNLOGIN.getCode(),Renum.UNLOGIN.getMsg());
        }
    }
}
